﻿using System.Security.Cryptography;
using System.Threading.Tasks;
using FDSimpleModelGenerator.Entities.CreateTables;
using FDSimpleModelGenerator.IRepositories;
using FDSimpleModelGenerator.IServices;

namespace FDSimpleModelGenerator.Services
{
    /// <summary>
    /// 创建的表信息服务
    /// </summary>
    public class TableService : BasicService<Table>, ITableService
    {
        private IColumnRepository _columnRepository;
        private IColumnIndexRepository _columnIndexRepository;

        public TableService(IBasicRepository<Table> basicRepository, IColumnRepository columnRepository,
            IColumnIndexRepository columnIndexRepository)
            : base(basicRepository)
        {
            _columnRepository = columnRepository;
        }

        public async Task<bool> AddOrUpdateTable(Table table)
        {
            var sql = "select * from gen_table where name=@Name and \"database\"=@Database";
            var reposiorty = Repository<ITableRepository>();
            var tab = await reposiorty.QueryAsync<Table>(sql, new { table.Name, table.Database });
            if (tab == null)
            {
                var resTable = reposiorty.Add(table);

                if (resTable)
                {
                    var resC = await _columnRepository.AddBatchAsync(table.Columns, table.Id);
                    var resI = await _columnIndexRepository.AddBatchAsync(table.Indexes, table.Id);

                    return resI && resC;
                }
            }
            else
            {

            }

            return false;
        }
    }
}
